winsafe\gui\native_controls/edit.rs
1use std::any::Any;
2use std::marker::PhantomPinned;
3use std::pin::Pin;
4use std::sync::Arc;
5
6use crate::co;
7use crate::decl::*;
8use crate::gui::{privs::*, *};
9use crate::msg::*;
10use crate::prelude::*;
11
12struct EditObj {
13 base: BaseCtrl,
14 events: BaseCtrlEvents,
15 _pin: PhantomPinned,
16}
17
18native_ctrl! { Edit: EditObj => GuiEventsEdit;
19 /// Native
20 /// [edit](https://learn.microsoft.com/en-us/windows/win32/controls/about-edit-controls)
21 /// (text box) control.
22}
23
24impl Edit {
25 /// Instantiates a new `Edit` object, to be created on the parent window
26 /// with [`HWND::CreateWindowEx`](crate::HWND::CreateWindowEx).
27 ///
28 /// # Panics
29 ///
30 /// Panics if the parent window was already created – that is, you cannot
31 /// dynamically create an `Edit` in an event closure.
32 ///
33 /// # Examples
34 ///
35 /// ```no_run
36 /// use winsafe::{self as w, prelude::*, gui};
37 ///
38 /// let wnd: gui::WindowMain; // initialized somewhere
39 /// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
40 ///
41 /// let txt = gui::Edit::new(
42 /// &wnd,
43 /// gui::EditOpts {
44 /// position: gui::dpi(10, 10),
45 /// width: gui::dpi_x(120),
46 /// ..Default::default()
47 /// },
48 /// );
49 /// ```
50 #[must_use]
51 pub fn new(parent: &(impl GuiParent + 'static), opts: EditOpts) -> Self {
52 let ctrl_id = auto_id::set_if_zero(opts.ctrl_id);
53 let new_self = Self(Arc::pin(EditObj {
54 base: BaseCtrl::new(ctrl_id),
55 events: BaseCtrlEvents::new(parent, ctrl_id),
56 _pin: PhantomPinned,
57 }));
58
59 let self2 = new_self.clone();
60 let parent2 = parent.clone();
61 let text2 = opts.text.to_owned();
62 parent
63 .as_ref()
64 .before_on()
65 .wm(parent.as_ref().wnd_ty().creation_msg(), move |_| {
66 self2.0.base.create_window(
67 opts.window_ex_style,
68 "EDIT",
69 Some(&text2),
70 opts.window_style | opts.control_style.into(),
71 opts.position.into(),
72 SIZE::with(opts.width, opts.height),
73 &parent2,
74 );
75 ui_font::set(self2.hwnd());
76 parent2
77 .as_ref()
78 .add_to_layout(self2.hwnd(), opts.resize_behavior);
79 Ok(0) // ignored
80 });
81
82 new_self.default_message_handlers(parent);
83 new_self
84 }
85
86 /// Instantiates a new `Edit` object, to be loaded from a dialog resource
87 /// with [`HWND::GetDlgItem`](crate::HWND::GetDlgItem).
88 ///
89 /// # Panics
90 ///
91 /// Panics if the parent dialog was already created – that is, you cannot
92 /// dynamically create an `Edit` in an event closure.
93 #[must_use]
94 pub fn new_dlg(
95 parent: &(impl GuiParent + 'static),
96 ctrl_id: u16,
97 resize_behavior: (Horz, Vert),
98 ) -> Self {
99 let new_self = Self(Arc::pin(EditObj {
100 base: BaseCtrl::new(ctrl_id),
101 events: BaseCtrlEvents::new(parent, ctrl_id),
102 _pin: PhantomPinned,
103 }));
104
105 let self2 = new_self.clone();
106 let parent2 = parent.clone();
107 parent.as_ref().before_on().wm_init_dialog(move |_| {
108 self2.0.base.assign_dlg(&parent2);
109 parent2
110 .as_ref()
111 .add_to_layout(self2.hwnd(), resize_behavior);
112 Ok(true) // ignored
113 });
114
115 new_self.default_message_handlers(parent);
116 new_self
117 }
118
119 fn default_message_handlers(&self, parent: &(impl GuiParent + 'static)) {
120 let self2 = self.clone();
121 let parent2 = parent.clone();
122 parent
123 .as_ref()
124 .before_on()
125 .wm_command(self.ctrl_id(), co::EN::CHANGE, move || {
126 // EN_CHANGE is first sent to the control before CreateWindowEx()
127 // returns, so if the user handles EN_CHANGE, the Edit HWND won't be
128 // set yet. So we set the HWND here.
129 if *self2.hwnd() == HWND::NULL {
130 let hctrl = parent2
131 .as_ref()
132 .hwnd()
133 .GetDlgItem(self2.ctrl_id())
134 .expect(DONTFAIL);
135 self2.0.base.set_hwnd(hctrl);
136 }
137 Ok(())
138 });
139 }
140
141 /// Hides any balloon tip by sending an
142 /// [`em::HideBalloonTip`](crate::msg::em::HideBalloonTip) message.
143 pub fn hide_balloon_tip(&self) -> SysResult<()> {
144 unsafe { self.hwnd().SendMessage(em::HideBalloonTip {}) }
145 }
146
147 /// Limits the number of characters that can be type by sending an
148 /// [`em::SetLimitText`](crate::msg::em::SetLimitText) message.
149 pub fn limit_text(&self, max_chars: Option<u32>) {
150 unsafe {
151 self.hwnd().SendMessage(em::SetLimitText { max_chars });
152 }
153 }
154
155 /// Sets the selection range of the text by sending an
156 /// [`em::SetSel`](crate::msg::em::SetSel) message.
157 ///
158 /// # Examples
159 ///
160 /// Selecting all text in the control:
161 ///
162 /// ```no_run
163 /// use winsafe::{self as w, prelude::*, gui};
164 ///
165 /// let my_edit: gui::Edit; // initialized somewhere
166 /// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
167 /// # let my_edit = gui::Edit::new(&wnd, gui::EditOpts::default());
168 ///
169 /// my_edit.set_selection(0, -1);
170 /// ```
171 ///
172 /// Clearing the selection:
173 ///
174 /// ```no_run
175 /// use winsafe::gui;
176 ///
177 /// let my_edit: gui::Edit; // initialized somewhere
178 /// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
179 /// # let my_edit = gui::Edit::new(&wnd, gui::EditOpts::default());
180 ///
181 /// my_edit.set_selection(-1, -1);
182 /// ```
183 pub fn set_selection(&self, start: i32, end: i32) {
184 unsafe {
185 self.hwnd().SendMessage(em::SetSel { start, end });
186 }
187 }
188
189 /// Sets the text by calling
190 /// [`HWND::SetWindowText`](crate::HWND::SetWindowText).
191 pub fn set_text(&self, text: &str) -> SysResult<()> {
192 self.hwnd().SetWindowText(text)?;
193 Ok(())
194 }
195
196 /// Displays a balloon tip by sending an
197 /// [`em::ShowBalloonTip`](crate::msg::em::ShowBalloonTip) message.
198 pub fn show_ballon_tip(&self, title: &str, text: &str, icon: co::TTI) -> SysResult<()> {
199 let mut title16 = WString::from_str(title);
200 let mut text16 = WString::from_str(text);
201
202 let mut info = EDITBALLOONTIP::default();
203 info.set_pszTitle(Some(&mut title16));
204 info.set_pszText(Some(&mut text16));
205 info.ttiIcon = icon;
206
207 unsafe { self.hwnd().SendMessage(em::ShowBalloonTip { info: &info }) }
208 }
209
210 /// Retrieves the text by calling
211 /// [`HWND::GetWindowText`](crate::HWND::GetWindowText).
212 #[must_use]
213 pub fn text(&self) -> SysResult<String> {
214 self.hwnd().GetWindowText()
215 }
216}
217
218/// Options to create an [`Edit`](crate::gui::Edit) programmatically with
219/// [`Edit::new`](crate::gui::Edit::new).
220pub struct EditOpts<'a> {
221 /// Text of the control to be
222 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
223 ///
224 /// Defaults to empty string.
225 pub text: &'a str,
226 /// Left and top position coordinates of control within parent's client
227 /// area, to be
228 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
229 ///
230 /// Defaults to `gui::dpi(0, 0)`.
231 pub position: (i32, i32),
232 /// Control width to be
233 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
234 ///
235 /// Defaults to `gui::dpi_x(100)`.
236 pub width: i32,
237 /// Control height to be
238 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
239 ///
240 /// Defaults to `gui::dpi_y(23)`.
241 ///
242 /// **Note:** You should change the default height only in a multi-line
243 /// edit, otherwise it will look off.
244 pub height: i32,
245 /// Edit styles to be
246 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
247 ///
248 /// Defaults to `ES::AUTOHSCROLL | ES::NOHIDESEL`.
249 ///
250 /// Suggestions:
251 /// * add `ES::PASSWORD` for a password input;
252 /// * add `ES::NUMBER` to accept only numbers;
253 /// * replace with `ES::MULTILINE | ES::WANTRETURN | ES::AUTOVSCROLL | ES::NOHIDESEL` for a multi-line edit.
254 pub control_style: co::ES,
255 /// Window styles to be
256 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
257 ///
258 /// Defaults to `WS::CHILD | WS::GROUP | WS::TABSTOP | WS::VISIBLE`.
259 pub window_style: co::WS,
260 /// Extended window styles to be
261 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
262 ///
263 /// Defaults to `WS_EX::LEFT | WS_EX::CLIENTEDGE`.
264 pub window_ex_style: co::WS_EX,
265
266 /// The control ID.
267 ///
268 /// Defaults to an auto-generated ID.
269 pub ctrl_id: u16,
270 /// Horizontal and vertical behavior of the control when the parent window
271 /// is resized.
272 ///
273 /// **Note:** You should use `Vert::Resize` only in a multi-line edit.
274 ///
275 /// Defaults to `(gui::Horz::None, gui::Vert::None)`.
276 pub resize_behavior: (Horz, Vert),
277}
278
279impl<'a> Default for EditOpts<'a> {
280 fn default() -> Self {
281 Self {
282 text: "",
283 position: dpi(0, 0),
284 width: dpi_x(100),
285 height: dpi_y(23),
286 control_style: co::ES::AUTOHSCROLL | co::ES::NOHIDESEL,
287 window_style: co::WS::CHILD | co::WS::GROUP | co::WS::TABSTOP | co::WS::VISIBLE,
288 window_ex_style: co::WS_EX::LEFT | co::WS_EX::CLIENTEDGE,
289 ctrl_id: 0,
290 resize_behavior: (Horz::None, Vert::None),
291 }
292 }
293}